package com.xiebishe.mylibrary.common.groupAdapter;


import java.util.ArrayList;
import java.util.List;

public abstract class RecyclerDataGroupAdapter<DATA> extends RecyclerGroupImplAdapter {
    private List<DATA> dataList = new ArrayList<>();

    public RecyclerDataGroupAdapter() {
        super();
    }


    public final void setData(List<DATA> dataList) {
        this.dataList.clear();

        if (dataList == null || dataList.isEmpty()) {
            super.removeAll();
            return;
        }
        this.dataList.addAll(dataList);
        ArrayList<RecyclerAdapter<?>> adapters = new ArrayList<>(dataList.size());
        for (DATA data : dataList) {
            adapters.add(createAdapter(data));
        }
        super.update(adapters);
    }

    public final void addData(DATA item) {
        this.dataList.add(item);
        RecyclerAdapter<?> adapter = createAdapter(item);
        super.add(adapter);
    }

    public final void addData(DATA item, int position) {
        this.dataList.add(position, item);
        RecyclerAdapter<?> adapter = createAdapter(item);
        super.add(adapter, position);
    }

    public final void addDataAll(List<DATA> dataList) {
        if (dataList == null || dataList.isEmpty()) {
            return;
        }
        this.dataList.addAll(dataList);
        ArrayList<RecyclerAdapter<?>> adapters = new ArrayList<>(dataList.size());
        for (DATA data : dataList) {
            adapters.add(createAdapter(data));
        }
        super.addAll(adapters);
    }

    public final void removeAllData() {
        this.dataList.clear();
        super.removeAll();
    }

    public final void removeDataAt(int position) {
        this.dataList.remove(position);
        super.remove(position);
    }

    public final boolean removeData(DATA item) {
        int i = this.dataList.indexOf(item);
        if (i > 0) {
            remove(i);
            return true;
        }
        return false;
    }

    protected abstract RecyclerAdapter<?> createAdapter(DATA item);
}
